package com.dkd.day20250620;

import java.util.ArrayList;

public class SolutiongenerateParenthesis {
    public static void main(String[] args) {

    }
    public ArrayList<String> generateParenthesis (int n) {
        // write code here
        ArrayList<String> res = new ArrayList<>();
        backtrack(res, "", 0, 0, n);
        return res;
    }

    private void backtrack(ArrayList<String> res, String curr, int open, int close, int max) {
        // 终止条件：当前字符串长度 = 2n
        if (curr.length() == 2 * max) {
            res.add(curr);
            return;
        }
        // 添加左括号的条件：剩余左括号数量 > 0
        if (open < max) {
            backtrack(res, curr + "(", open + 1, close, max);
        }
        // 添加右括号的条件：剩余右括号数量 > 0 且 已用左括号 > 已用右括号
        if (close < open) {
            backtrack(res, curr + ")", open, close + 1, max);
        }
    }
}
